package dao

import (
	"device_srv/device"
	"device_srv/models"
	"errors"
	"go.uber.org/zap"
	"gorm.io/gorm"
	"smart-health-platforms/pkg"
)

// BrandsAdd 品牌创建
func BrandsAdd(in *device.BrandsAddRequest) (*models.Brands, error) {
	//接收参数
	brands := models.Brands{
		BrandName:        in.BrandName,
		BrandDescription: in.BrandDescription,
	}
	err := brands.CreateBrands()
	pkg.Info("品牌信息创建成功",
		zap.Int("id", int(brands.Id)),
		zap.String("DeviceName", brands.BrandName),
	)
	if err != nil {
		pkg.Warn("品牌信息创建失败")
		return nil, errors.New("品牌信息创建失败")
	}
	return &brands, err
}

// BrandsDetail 品牌详情
func BrandsDetail(in *device.BrandsDetailRequest) (*models.Brands, error) {
	brands := models.Brands{
		Id: uint(in.Id),
	}
	err := brands.BrandsDetail()
	pkg.Info("品牌信息详情获取成功",
		zap.Int("id", int(brands.Id)),
		zap.String("DeviceName", brands.BrandName),
	)
	if err != nil {
		pkg.Warn("品牌信息详情获取失败")
		return nil, errors.New("品牌信息详情获取失败")
	}
	return &brands, err

}

// BrandsUpdate 品牌修改
func BrandsUpdate(in *device.BrandsUpdateRequest) (*models.Brands, error) {
	var brands models.Brands
	brands.Id = uint(in.Id)

	err := brands.GetBrandsById(in.Id)
	if err != nil {
		return nil, errors.New("品牌ID查找失败")
	}
	if brands.BrandName == "" {
		return nil, errors.New("该品牌信息不存在，禁止修改信息")
	}
	brands.BrandName = in.BrandName
	brands.BrandDescription = in.BrandDescription
	err = brands.BrandsUpdate()
	pkg.Info("品牌信息修改成功",
		zap.Int("id", int(brands.Id)),
		zap.String("DeviceName", brands.BrandName),
	)
	if err != nil {
		pkg.Warn("品牌信息修改失败")
		return nil, errors.New("品牌信息修改失败")
	}
	return &brands, err
}

// BrandsDelete 品牌删除
func BrandsDelete(in *device.BrandsDeleteRequest) (*models.Brands, error) {
	brands := models.Brands{
		Id: uint(in.Id),
	}
	err := brands.GetBrandsById(int64(brands.Id))
	if err != nil {
		return nil, errors.New("品牌ID查找失败")
	}
	if brands.Id == 0 {
		return nil, errors.New("该品牌信息不存在，禁止删除")
	}
	err = brands.BrandsDelete()
	if err != nil {
		pkg.Warn("品牌信息删除失败")
		return nil, errors.New("品牌信息删除失败")
	}
	return &brands, err
}

// BrandsList 品牌列表
func BrandsList(in *device.BrandsListRequest) ([]*device.BrandsList, error) {

	var bra models.Brands
	list, err := bra.GetBrandsList(int(in.Page), int(in.PageSize))
	if err != nil {
		return nil, errors.New("品牌信息列表展示失败")
	}
	var brandsList []*device.BrandsList
	for _, brand := range list {
		lists := device.BrandsList{
			Id:               int64(brand.Id),
			BrandName:        brand.BrandName,
			BrandDescription: brand.BrandDescription,
		}
		brandsList = append(brandsList, &lists)
	}
	return brandsList, err
}

// 分页
func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {

		if page <= 0 {
			page = 1
		}

		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}
